package net.lzzy.service;

import net.lzzy.entity.Role;
import net.lzzy.entity.User;
import net.lzzy.repository.RoleRepository;
import net.lzzy.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;

@Service
public class UserService implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private RoleRepository roleRepository;


    //实现UserDetailsService默认方法
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        User user = userRepository.findByUsername(s);
        if(user == null){
            throw new UsernameNotFoundException("用户不存在");
        }
        return user;
    }

    //实现注册功能，根据用户名和邮箱查询当前用户是否已存在
    public boolean register(String email, String username, String password){
        if (userRepository.findByUsername(username) != null) {
            return false;
        }
        else if (userRepository.findByEmail(email) != null){
            return false;
        }
        else {
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            User user = new User();
            user.setUsername(username);
            user.setPassword(encoder.encode(password));
            user.setRoles(Arrays.asList(roleRepository.findById(2).get()));
            user.setDate(new Date());
            userRepository.save(user);
            return true;
        }
    }
}
